# from math import e
import time
import threading
import signal
 
 
class Task(threading.Thread):
 
    def __init__(self):
        threading.Thread.__init__(self)
 
        # shutdown_flag 用于关闭线程
        self.shutdown_flag = threading.Event()
 
        # ... Other thread setup code here ...
 
    def run(self):
        print(f'Thread #{self.ident} started')
 
        while not self.shutdown_flag.is_set():
            # 线程代码可以放在这里            
            print(f"Thread #{self.ident} is running...")
            time.sleep(1)
 
        # ... Clean code put here ...
        print(f'Thread #{self.ident} stopped')
 
 
class ServiceExit(Exception):
    """
    自定义1个异常类，用于退出线程
    """
    def __init__(self,message="force to quit"):
        self.message = message
        super(ServiceExit,self).__init__(self.message)
    
    # __str__ is to print() the message
    def __str__(self):
        return(repr(self.message))
 
 
def handler_quit(signum, frame):
    """信号处理函数"""
    print('Caught signal %d' % signum)
    raise ServiceExit("当前线程被强制退出...")
 
 
def main():
 
    # 注册信号回调函数
    signal.signal(signal.SIGTERM, handler_quit)
    signal.signal(signal.SIGINT, handler_quit)
 
    print('Starting main program')
 
    # Start the sub threads
    try:
        t1 = Task()
        t2 = Task()
        t1.start()
        t2.start()
 
        # 保持主线程运行，否则无法收到信号
        while True:
            time.sleep(0.5)
 
    except ServiceExit as e:
        t1.shutdown_flag.set()
        t2.shutdown_flag.set()
        # Wait for the threads to close...
        t1.join()
        t2.join()
        print(e.message)
 
    print('Exiting main program')
 
 
if __name__ == '__main__':
    main()

